#include "SoftwarePackageParser.h"

#include "CertificationParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

SoftwarePackageParser::SoftwarePackageParser(
    QStringParser *&_nameParser
    , QStringParser *&_vendorParser
    , QStringParser *&_revisionParser
    , QStringParser *&_modelParser
    , CertificationParser *&_certificationParser
):    m_nameParser(_nameParser)
    , m_vendorParser(_vendorParser)
    , m_revisionParser(_revisionParser)
    , m_modelParser(_modelParser)
    , m_certificationParser(_certificationParser)
{

}

bool SoftwarePackageParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new SoftwarePackage());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("vendor")))
    {
        data = reader->attributes().value(QStringLiteral("vendor"));
        if (!m_vendorParser->parse(reader, data))
            return false;
        m_result->vendor = m_vendorParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("vendor: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("revision")))
    {
        data = reader->attributes().value(QStringLiteral("revision"));
        if (!m_revisionParser->parse(reader, data))
            return false;
        m_result->revision = m_revisionParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("revision: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("model")))
    {
        data = reader->attributes().value(QStringLiteral("model"));
        if (!m_modelParser->parse(reader, data))
            return false;
        m_result->modelOptional = Optional<QString>(m_modelParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Certification"))
        {
            if (!m_certificationParser->parse(reader))
                return false;
            auto result = m_certificationParser->result();
            m_result->certificationList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

SoftwarePackage *SoftwarePackageParser::result()
{
    return m_result.take();
}

}